package com.proyecto.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.proyecto.modelo.Pais;


/**
 * Clase que implementa los metodos de la interfaz UsuarioDao. 
 * Utilizada para generar consultas a la DB.
 * Extiende {@link SpringHibernateDao}
 * 
 */
@Repository
public class PaisDaoImpl extends SpringHibernateDao<Pais> implements PaisDao

{
	/**
	 * @param sessionFactory Objeto para abrir una sesion a la DB.
	 * Constructor de la clase.
	 */
	@Autowired
	public PaisDaoImpl(SessionFactory sessionFactory) {
		super(sessionFactory);

	}

	
	/* (non-Javadoc)
	 * @see org.cimientos.intranet.dao.base.SpringHibernateDao#getObjetoManejado()
	 */
	@Override
	protected Class<Pais> getObjetoManejado() {
			return Pais.class;
	}


	@Override
	public Pais devolverPais(String nombre) {
		// TODO Auto-generated method stub
Pais pais;
		
		
	    SessionFactory sessionFactory;
		sessionFactory = new Configuration().configure().buildSessionFactory();
		
		Session session = sessionFactory.openSession();
		
		session.beginTransaction();
		
		Criteria crit=session.createCriteria(Pais.class);
		List listapaises = crit.add(Restrictions.eq("nombre",nombre)).list();
		
		
           if (listapaises.isEmpty())	{
        	   return null;
           }
           else
		
			   
			   pais=(Pais) listapaises.get(0);
		 		return pais;
		
	}


	@Override
	public void agregarPais(Pais p) {
		SessionFactory sessionFactory;
 		sessionFactory = new Configuration().configure().buildSessionFactory();
 		
 		Session session = sessionFactory.openSession();
 		
 		session.beginTransaction();
 		
 		session.persist(p);
		session.getTransaction().commit();
        
		session.close();

		
	}


	@Override
	public boolean eliminarPais(String nom) {
		// TODO Auto-generated method stub
		Pais pais;
    	SessionFactory sessionFactory;
		sessionFactory = new Configuration().configure().buildSessionFactory();
		
		Session session = sessionFactory.openSession();
		
		session.beginTransaction();
		
    	
    	pais=devolverPais(nom);
    	if (pais!=null){
    		session.delete(pais);
    		return true;
    	} else return false;
    	
	}



}
